'use strict';
//1.正确使用egg搭建后台服务（10分）
const axios = require("axios");
let svgCaptcha = require('svg-captcha');
const Controller = require('egg').Controller;
const path = require('path');
const fs = require('mz/fs');
const jwt = require("jsonwebtoken");
const createRule = {
    name: 'string',
    pwd: "string",
};
const captchaRule = {
    captcha: "string"
}
class loginController extends Controller {
    async getuser() {
        const { ctx } = this;
        const { code } = ctx.query;
        let config = ctx.app.config.gitee
        let res = await axios.post("https://gitee.com/oauth/token", {
            grant_type: "authorization_code",
            code,
            client_id: config.client_id,
            redirect_uri: config.redirect_uri,
            client_secret: config.client_secret,
        });

        let access_token = res.data.access_token
        let user = await axios.get("https://gitee.com/api/v5/user", {
            params: {
                access_token
            }
        })
        if (user.status === 200) {
            ctx.body = {
                code: 0,
                data: user.data,
                token: jwt.sign({ name: user.data.name, id: user.data.id }, 'aj', { expiresIn: '10h' })
            }
        } else {
            ctx.body = {
                code: 1,
                msg: 'user.data'
            }
        }
    }
    async getcaptcha() {
        const { ctx } = this;
        let captcha = svgCaptcha.create({
            size: 3,
            width: 100,
            height: 40,
        })
        ctx.session.captcha = captcha.text;
        ctx.type = "svg"
        ctx.body = captcha.data;
    }
    async login() {
        const { ctx } = this;
        ctx.validate({ ...createRule, ...captchaRule }, ctx.request.body);
        const { name, captcha } = ctx.request.body;
        if (captcha.toLowerCase() !== ctx.session.captcha.toLowerCase()) {
            ctx.body = {
                code: 1,
                msg: "验证码错误"
            }
            return;
        }
        const user = await ctx.service.login.getUser(name);
        if (!user) {
            ctx.body = {
                code: 4,
                msg: "用户名不存在，请先注册"
            }
            return;
        }
        const res = await ctx.service.login.login(ctx.request.body);
        console.log(res);
        const token = jwt.sign({ name: res[0].name, id: res[0].id }, "aj", { expiresIn: "10h" })
        if (res.length > 0) {
            ctx.body = {
                code: 2,
                msg: "登录成功",
                token
            };
        } else {
            ctx.body = {
                code: 4,
                msg: "登录失败"
            };
        }
    }
    async register() {
        const { ctx } = this;
        ctx.validate(createRule, ctx.request.body);
        let {name} = ctx.request.body;
        const user = await ctx.service.login.getUser(name);
        if (user) {
            ctx.body = {
                code: 4,
                msg: "用户名已存在，请登录"
            }
            return;
        }
        const res = await ctx.service.login.register(ctx.request.body);
        if (res.affectedRows === 1) {
            ctx.body = {
                code: 2,
                msg: "注册成功"
            }
        } else {
            ctx.body = {
                code: 4,
                msg: "注册失败"
            }
        }
    }
    async upload() {
        const ctx = this.ctx;
        const file = ctx.request.files[0];
        const name = 'sun1233/' + path.basename(file.filename);
        let result;
        try {
            result = await ctx.oss.put(name, file.filepath);
        } finally {
            await fs.unlink(file.filepath);
        }
        if (result) {
            ctx.body = {
                code: 200,
                url: result.url
            }
        } else {
            ctx.body = 'please select a file to upload！';
        }
    }
}

module.exports = loginController;
